<?php

declare(strict_types=1);

namespace app\api\controller;

use think\facade\Request;
use think\facade\Db;
use app\api\controller\WxpayService;
use app\api\controller\Withdrawal;
use app\model\zs\ZsMemberCoupon;
use app\model\zs\ZsMemberCouponOrder;
use app\model\zs\ZsMemberCouponProvide;
use app\model\zsnew\ZsnewKcSale;
use app\model\zs\ZsMealDetailsStore;
use app\model\zsnew\ZsnewSaledetails;
use app\model\zs\ZsBusiness;
use app\model\zs\ZsMmealKcLog;
use app\model\crm\XFBONUSLEDGER;
use app\model\crm\XFBONUSPOOL;

class Order
{
    /**
     * 会员订单详情
     * @return mixed
     */
    public function orderInfo(){
        $docno = Request::param('docno');

        $korder = ZsMealDetailsStore::where('order_on' , $docno)
            ->find();
        //var_dump($korder);return;
        $bonus = 0;
        if(empty($korder)){
            $order = ZsnewKcSale::where('XF_DOCNO' , $docno)->find();
            $saleList = ZsnewSaledetails::where('XF_DOCNO' , $docno)->select();
            if(!$order){
                return jsonData(0, '没有这个订单');
            }
            if($order['XF_VIPCODE']){
                $bonusList = XFBONUSLEDGER::where('XF_DOCNO', $docno)->select();
                /*$CurrentBonus = XFBONUSPOOL::where('XF_VIPCODE', $order['XF_VIPCODE'])
                    ->whereTime('EB_LASTMODIFY_DATETIME', '<', $order['XF_CREATETIME'])
                    ->order('EB_LASTMODIFY_DATETIME','desc')
                    ->limit(1)
                    ->select();*/
                //var_dump($bonus);
                if($bonusList){
                    $bonus = $bonusList[0]['XF_BONUS'];
                }
            }
            $data = [
                'details' => $saleList,
                'order' => $order,
                'bonus' => [
                    'XF_BONUS' => $bonus,
                    'CurrentBonus' => 0 //怎么查询当次消费剩余积分
                ]
            ];

            return jsonData(1, '查询成功',$data);

        }else{
            $order = ZsMealDetailsStore::where('order_on' , $docno)
                ->find();
            if(!$order){
                return jsonData(0, '没有这个订单');
            }
            $bonus = ZsMmealKcLog::where(['order_on' => $docno, 'type' => 2])
                ->find();
            $orderarr['XF_DOCNO'] = $order['order_on'];
            $orderarr['XF_VIPCODE'] = $order['vipcode'];
            $orderarr['XF_CREATETIME'] = $order['create_at'];
            $orderarr['XF_SELLINGAMOUNT'] = $order['real_amount']+$order['ticket_amount']+$order['integral'];

            $payment = $order['payment']==='WX'?'微信':($order['payment']==='AL'?'支付宝':'余额支付');
            $brandname = ZsBusiness::where('id' , $order['businessid'])->column('brandname');
            $orderarr['XF_STORENAME'] = $brandname;

            $details = [[
                'XF_PLU' => $order['itemCode'],
                'XF_TENDERDESC' => $payment,
                'XF_PAYAMOUNT' => $order['real_amount'],
                'XF_DESCI' => '',
            ], [
                'XF_PLU' => $order['itemCode'],
                'XF_TENDERDESC' => '优惠券',
                'XF_PAYAMOUNT' => $order['ticket_amount'],
                'XF_DESCI' => '',
            ], [
                'XF_PLU' => $order['itemCode'],
                'XF_TENDERDESC' => '积分',
                'XF_PAYAMOUNT' => $order['integral'],
                'XF_DESCI' => '',
            ]];

            $data = [
                'details' => $details,
                'order' => $orderarr,
                'bonus' => [
                    'XF_BONUS' => $bonus['BonusEarn'],
                    'CurrentBonus' => $bonus['CurrentBonus']
                ]
            ];

            return jsonData(1, '查询成功',$data);
        }
    }
    /**
     * 会员订单查询
     * @return mixed
     */
    public function getOrder(){
        $vipcode = Request::param('vipcode');
        $page = (int)Request::param('page');
        $interval = Request::param('intervals');
        $startDate = Request::param('startDate');
        $endDate = Request::param('endDate');
        if(!$startDate){
            $startDate = date('Y-01-01 00:00:00',time());
            $endDate = date('Y-m-d 23:59:59',time());
        }
        //本月数据
        if($interval == 'month'){
            $startDate = date('Y-m-01 00:00:00',time());
            $endDate = date('Y-m-d 23:59:59',time());
        }
        //本周数据
        if($interval == 'week'){
            $startDate = date('Y-m-d 00:00:00',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
            $endDate = date('Y-m-d 23:59:59',time());
        }

        $rs = ZsnewKcSale::where('XF_VIPCODE', $vipcode)
            ->whereBetweenTime('XF_CREATETIME', $startDate, $endDate)
            ->order('XF_CREATETIME', 'desc')
            ->page($page,10)
            ->select();
        //var_dump($startDate,$endDate);
        $count = ZsnewKcSale::where('XF_VIPCODE',$vipcode)
            ->whereBetweenTime('XF_CREATETIME', $startDate, $endDate)
            ->count();

        $data = [
            'list' => $rs,
            'count' => $count
        ];
        return jsonData(1, '查询成功', $data);
    }
    /**
     * 生成订单
     */
    public function create()
    {
        $openid = Request::header('openid');
        $total = Request::param('total');
        $uid = Db::name('user')->where('wechat_openid', $openid)->find()['uid'];
        // 生成订单信息
        $data = [
            'uid' => $uid,
            'total' => $total,
            'order_sn' => get_sn(),
            'create_time' => time(),
            'update_time' => time(),
            'pay_status' => 0,
        ];
        Db::name('order')->insert($data);
        $order = Db::name('order')->where('order_sn', $data['order_sn'])->find();
        // var_dump($order);


        // 统一下单信息
        $mchid = '商户号';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
        $appid = '公众号appid';  //微信支付申请对应的公众号的APPID
        $appKey = '公众号密钥';   //微信支付申请对应的公众号的APP Key
        $apiKey = '商户支付API密钥';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
        $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey, $openid);

        // 统一下单
        $outTradeNo = $data['order_sn'];     //商品订单号
        $totalFee = $order['total'];          //付款金额，单位:元
        $orderName = '微信零钱';    //订单标题
        $notifyUrl = 'https://api.lq.galaxy-x.cn/api/Order/notify';     //付款成功后的回调地址(不要有问号)
        $timestamp = time();      //付款时间
        $jsApiParameters = $wxPay->createJsBizPackage($openid, $totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp);
        // $jsApiParameters = json_decode($jsApiParameters);
        // var_dump($jsApiParameters);
        return jsonData(1, '订单创建成功', $jsApiParameters);
    }

    /**
     * 用户订单列表
     */
    public function lists()
    {
        $openid = Request::header('openid');
        $page = Request::param('page');
        $page_size = Request::param('page_size');
        $uid = Db::name('user')->where('wechat_openid', $openid)->find()['uid'];
        $list = Db::name('order')->where(array('uid' => $uid, 'pay_status' => 1))->order('update_time', 'desc');
        $total = $list->select()->count();
        $order = $list->page((int)$page, (int)$page_size)->select()->each(function ($item, $key) {
            $item['type'] = 1;
            return $item;
        });
        // $order = $list->page((int)$page, (int)$page_size)->select();
        $data = [
            'data' => $order,
            'total' => $total
        ];
        // var_dump($list);
        // die;
        return jsonData(1, '查询成功', $data);
    }

    /**
     * 更新用户总支付订单信息
     */
    public function updateUserOrder($result)
    {
        // $uid = Request::param('uid');
        // 微信支付订单回调会调用多次，所以查询该用户已支付的订单，来累计订单额，更新到用户表
        $uid = Db::name('order')->where('order_sn', $result['out_trade_no'])->find()['uid'];
        $orders = Db::name('order')->where(array('uid' => $uid, 'pay_status' => 1))->select()->toArray();
        $total_amount = 0;
        for ($row = 0; $row < count($orders); $row++) {
            $total_amount = $total_amount + $orders[$row]['total'];
        };
        $data['pay_money'] = $total_amount;
        $data['pay_order'] = count($orders);
        // 更新用户总支付金额及订单数
        Db::name('user')->where('uid', $uid)->update($data);
    }

    /**
     * 微信支付回调
     */
    public function notify()
    {
        Db::startTrans();
        try {
            $testxml = file_get_contents("php://input");
            $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
            $result = json_decode($jsonxml, true);
            if (is_array($result)) {
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    // $order = Db::name('order')->where(array('order_sn' => $result['out_trade_no'], 'pay_status' => 0))->find();
                    $pay_data['pay_status'] = 1;
                    $pay_data['update_time'] = time();
                    Db::name('order')->where(array('order_sn' => $result['out_trade_no'], 'pay_status' => 0))->update($pay_data);
                    // 更新用户已支付的订单额
                    $this->updateUserOrder($result);
                    // 创建提现订单
                    $withdrawal = new Withdrawal();
                    $withdrawal->create($result);
                    // 发起提现
                    // $withdrawal -> userpay($wid);

                }
            }
            // 提交事务
            Db::commit();
            echo 'SUCCESS';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }

    /**
     * 申请退款
     */
    public function refund()
    {
        // member_coupon_provide表id
        $provide_id = Request::param('provide_id');
        $vipcode = Request::param('vipcode');
        $model_provide = ZsMemberCouponProvide::find($provide_id);
        if (!$model_provide) {
            return jsonData(0, '无领取记录');
        }

        if (!$model_provide['orderNo']) {
            return jsonData(0, '无订单号');
        }

        // if ($model_provide['amount'] <= 0 && $model_provide['integral'] <= 0) {
        if ($model_provide['amount'] <= 0) {
            return jsonData(0, '购买金额小于0，无法申请退款');
        }

        // 2021-4-15日起购买的优惠券才允许退款
        if ($model_provide['create_at'] < '2021-04-15') {
            return jsonData(0, '无法申请退款');
        }

        // 判断券是否本人领取
        if ($vipcode !== $model_provide['uid']) {
            return jsonData(0, '无权限');
        }

        // 状态不是正常时，不允许申请退款
        if ($model_provide['status'] != 0) {
            return jsonData(0, '无法申请退款');
        }

        $model_order = ZsMemberCouponOrder::where('docno', $model_provide['orderNo'])->find();
        if (!$model_order) {
            return jsonData(0, '无订单记录');
        }

        $model_coupon = ZsMemberCoupon::where('tid', $model_provide['tid'])->find();
        if (!$model_coupon) {
            return jsonData(0, '券不存在，无法申请退款');
        }

        $now = time();
        if ($now > strtotime($model_provide['valid_end'])) {
            return jsonData(0, '券已过期，无法申请退款');
        }

        // 将 member_coupon_provide 表的 status 段置为 3（表示退款状态）、将 member_coupon_order 表的 status 字段置为 2（表示退款状态）。
        $model_provide->status = 3;
        $model_provide->save();
        $model_order->status = 2;
        $model_order->save();
        return jsonData(1, 'ok', [
            'res_item' => [
                'refund_text' => '申请退款',
                'refund_btn_on' => false,
            ],
        ]);
    }
}
